package nio.filecopy;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 通过一个缓冲区进行文件的拷贝
 */
public class FileCopy {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("D:\\netty\\src\\nio\\filecopy\\test1.txt");
        FileChannel fileChannel1 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("D:\\netty\\src\\nio\\filecopy\\test2.txt");
        FileChannel fileChannel2 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel1.size());
        while (true){
            /**
             * 清空缓冲区数据
             */
            byteBuffer.clear();

            int read = fileChannel1.read(byteBuffer);
            if (read == -1){
                break;
            }
            byteBuffer.flip();
            fileChannel2.write(byteBuffer);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }
}
